import { useCallback, useRef, useState } from 'react'
import { Button, Typography } from '@mui/material'
import CropperImgUppy from '../../components/MyUppy/CropperImgUppy'
import Cropper from "react-cropper";
import { nanoid } from 'nanoid';
import "cropperjs/dist/cropper.css";
import './CropperPage.scss'

const CropperPage = () => {
  const uppyRef = useRef(null)
  const cropperRef = useRef(null)

  const [currentFileUrl, setCurrentFileUrl] = useState('')
  const [afterCropImg, setAfterCropImg] = useState('')
  const [cropFile, setCropFile] = useState(null)

  const removeAll = () => {
    console.log(uppyRef)
    uppyRef.current.removeAllFiles()
  }

  const onBeforeUpload = useCallback(async (files) => {
    console.log(files)
    uppyRef.current.removeAllFiles()
  }, [])

  const onBeforeFileAdd = useCallback((file) => {
    const currentUrl = URL.createObjectURL(file.data)
    setCurrentFileUrl(currentUrl)
  }, [])

  const onCrop = () => {
    const cropper = cropperRef.current.cropper
    // console.log(cropper.getCroppedCanvas())
    const dataUrl = cropper.getCroppedCanvas().toDataURL()
    setAfterCropImg(dataUrl)
    const blobFile = dataURLtoBlob(dataUrl)
    const cropFile = blobToFile(blobFile)
    setCropFile(cropFile)
  }

  // 将base64 转换成blob文件
  const dataURLtoBlob = (dataurl) => {
    var arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });//返回blob对象
  }

  const blobToFile = (theBlob) => {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = nanoid();
    return theBlob;
  }

  const downLoadFile = () => {
    const { name } = cropFile
    const url = URL.createObjectURL(cropFile)
    const el = document.createElement('a');
    el.style.display = 'none';
    el.setAttribute('target', '_blank');
    name && el.setAttribute('download', name);
    el.href = url;
    document.body.appendChild(el);
    el.click();
    document.body.removeChild(el);
  }

  return (
    <div className="CropperPage">
      <Typography>由于是个人框架，没有UI设计师参与，此页面仅在关注组件本身功能，不关注页面UI的观赏性。</Typography>
      <CropperImgUppy ref={uppyRef} onBeforeUpload={onBeforeUpload} onBeforeFileAdd={onBeforeFileAdd}></CropperImgUppy>
      <div>
        <Button onClick={() => removeAll()} variant='contained'>移除所有文件</Button>
      </div>
      <Typography>打开F12看调试界面，点击上传文件按钮的时候其实是可以收到文件的，此时我们可以拿着这些文件数据做任何事情。当然，在上传成功的时候也要将文件清除</Typography>
      <Typography>以下是cropper组件工具,组件还有很多属性没有放上来，仅在测试裁剪功能，不测试其他太多功能</Typography>
      <div>
        <Cropper
          src={currentFileUrl}
          style={{ height: 400, width: "100%" }}
          // Cropper.js options
          initialAspectRatio={16 / 9}
          viewMode={1}
          guides={false}
          crop={onCrop}
          ref={cropperRef}
        />
      </div>
      <Typography>用工具裁剪后的</Typography>
      <div><Button onClick={() => downLoadFile()} variant='contained'>下载组件工具裁剪后的文件</Button></div>
      <div>
        <img src={afterCropImg} />
      </div>
    </div>
  )
}

export default CropperPage